package com.cheer.ba.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.smileyloadingview.SmileyHeaderView;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.model.BannerModel;
import com.cheer.ba.model.CalculateMoneyModel;
import com.cheer.ba.model.ConstantModel;
import com.cheer.ba.model.OilDetailBannerModel;
import com.cheer.ba.model.OilDetailTagModel;
import com.cheer.ba.model.OilDetailsModel;
import com.cheer.ba.presenter.impl.FindOilPresenter;
import com.cheer.ba.presenter.impl.TransitPresenter;
import com.cheer.ba.utils.Currency;
import com.cheer.ba.utils.DensityUtils;
import com.cheer.ba.utils.Protect;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.TextViewUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.adapter.BannerPagerAdapter;
import com.cheer.ba.view.adapter.OilDetailBannerAdapter;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.widget.banner.BannerIndicator;
import com.cheer.ba.widget.banner.LoopViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 柴油批发详情
 */
public class OilDetailAty extends BaseCommAty {

    @BindView(R.id.id_oil_detail_xrefresh_view)
    XRefreshView mXRefreshView;

    //banner
    @BindView(R.id.id_oil_detail_banner)
    FrameLayout mLayoutBanner;
    //轮播图
    @BindView(R.id.id_oil_detail_viewpager)
    LoopViewPager mViewpager;
    //轮播图上的点
    @BindView(R.id.id_oil_detail_indicator)
    BannerIndicator mIndicator;
    //轮播图适配器
    private OilDetailBannerAdapter mBannerAdp;
    //得到banner
    private List<OilDetailBannerModel> mSaveBanners = new ArrayList<OilDetailBannerModel>();
    //点赞数量
    @BindView(R.id.id_zan_num_txt)
    TextView mTxtZanNum;
    //图片位置
    @BindView(R.id.id_pic_totla_txt)
    TextView mTxtPicLocation;
    private int mSaveTotalPic;

    //油源地址
    @BindView(R.id.id_oil_address_txt)
    TextView mTxtOilAddress;
    //油源
    @BindView(R.id.id_oil_type_txt)
    TextView mTxtOilCategory;
    //可开发票？
    @BindView(R.id.id_oil_Invoice_txt)
    TextView mTxtIsInvoce;
    //是否推荐
    @BindView(R.id.id_oil_recommend_img)
    ImageView mImgRecommend;
    //标题
    @BindView(R.id.id_oil_title_txt)
    TextView mTxtOilTitle;
    //价格
    @BindView(R.id.id_oil_price_txt)
    TextView mTxtOilPrice;
    @BindView(R.id.id_oil_price_linear)
    LinearLayout mLinearPrice;
    //库存
    @BindView(R.id.id_oil_kucun_txt)
    TextView mTxtOilKucun;
    //自提方式
    @BindView(R.id.id_oil_ziti_way_txt)
    TextView mTxtOilZitiWay;
    private String mSaveZitiNum;
    //配送方式
    @BindView(R.id.id_oil_send_way_txt)
    TextView mTxtOilSendWay;
    private String mSaveSendNum;
    //公司名称
    @BindView(R.id.id_company_name_txt)
    TextView mTxtCompanyName;
    //标准
    @BindView(R.id.id_oil_category_txt)
    TextView mTxtOilType;
    //密度
    @BindView(R.id.id_oil_density_txt)
    TextView mTxtOilDensity;
    //用户评价
    @BindView(R.id.id_comment_num_txt)
    TextView mTxtCommentNum;

    private String mOilId;
    //记录详情数据
    private OilDetailsModel mOilDetailsModel;
    //记录定金计算
    private CalculateMoneyModel mCalculateModel;

    private TransitPresenter mTransitPresenter;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_oil_detail, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new FindOilPresenter();

        mTransitPresenter = new TransitPresenter();
        mTransitPresenter.attachView(this);
    }

    @Override
    public boolean hasDataInPage() {
        return mOilDetailsModel != null;
    }

    @Override
    public void initView() {
        mOilId = getIntent().getStringExtra(IntentKey.General.KEY_ID);
        setTitleText("详情");

        //刷新
        setXRefreshView(mXRefreshView, true, false, false, false, new SmileyHeaderView(aty), null);
        //banner
        mLayoutBanner.getLayoutParams().height = DensityUtils.getScreenW(aty) * 344 / 750;
        mLayoutBanner.requestLayout();
        mViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                mTxtPicLocation.setText((position + 1) + "/" + mSaveTotalPic);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void initData() {
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false);
                stopRefresh(mXRefreshView, 4000);
            }
        });
        if (hasDataInPage()) {
            mXRefreshView.startRefresh();
        } else {
            loadData(!hasDataInPage());
        }
    }

    @OnClick({R.id.id_oil_address_txt, R.id.id_more_tag_txt, R.id.id_watch_comment_rela, R.id.id_call_kefu_btn, R.id.id_get_order_btn})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_oil_address_txt:
                //油源地址
                break;
            case R.id.id_more_tag_txt:
                // 更多参考属性
                if (null != mOilDetailsModel) {
                    List<OilDetailBannerModel> mOilS = mOilDetailsModel.certificateList;
                    if (null != mOilS && !mOilS.isEmpty()) {
                        OilDetailBannerModel model = mOilS.get(0);
                        if (model.fileType == 4) {
                            CommH5RefreshAty.startCommH5RefreshAty(aty, Protect.setPic(model.fileUrl), "参考属性");
                        } else {
                            Intent intent = new Intent(aty, OilDetailTagAty.class);
                            intent.putExtra(IntentKey.General.KEY_MODEL, mOilDetailsModel);
                            showActivity(aty, intent);
                        }
                    } else {
                        ToastUtil.showToast("暂无更多属性");
                    }
                } else {
                    ToastUtil.showToast("暂无更多属性");
                }
                break;
            case R.id.id_watch_comment_rela:
                //  查看用户评价
                if (isLogin(true)){
                    Intent intent = new Intent(aty, CommentListAty.class);
                    intent.putExtra(IntentKey.General.KEY_ID, mOilDetailsModel.uid);
                    showActivity(aty, intent);
                }
                break;
            case R.id.id_call_kefu_btn:
                //  联系客服
                StringUtils.telPhone(aty, "400 863 1886");
                break;
            case R.id.id_get_order_btn:
                if (isLogin(true)) {
                    //  立即下单
                    Intent pull = new Intent(aty, OilPullOrderAty.class);
                    pull.putExtra(IntentKey.General.KEY_MODEL, mOilDetailsModel);
                    pull.putExtra(IntentKey.General.KEY_DATA, mCalculateModel);
                    pull.putExtra(IntentKey.FindOil.ZITI_OIL_NUM, StringUtils.isEmpty(mSaveZitiNum) ? 0 : Double.parseDouble(mSaveZitiNum));
                    pull.putExtra(IntentKey.FindOil.SEND_OIL_NUM, StringUtils.isEmpty(mSaveSendNum) ? 0 : Double.parseDouble(mSaveSendNum));
                    showActivity(aty, pull);
                }
                break;
        }
    }

    /**
     * 加载数据
     *
     * @param isShowLoad 是否显示加载
     */
    public void loadData(boolean isShowLoad) {
        if (null == mOilDetailsModel) {
            //获得油详情
            ((FindOilPresenter) presenter).getOilDetails(mOilId, isShowLoad);
        }
        if (null == mCalculateModel) {
            //获得定金计算列表
            ((FindOilPresenter) presenter).getCalculateMoney();
        }
        stopRefresh(mXRefreshView, 4000);
    }

    /**
     * 处理接口返回数据
     */
    public void handleData() {
        //处理banner
        List<OilDetailBannerModel> mBanners = mOilDetailsModel.bannerList;
        if (null != mBanners && !mBanners.isEmpty()) {
            mLayoutBanner.setVisibility(View.VISIBLE);
            mSaveBanners.clear();
            mSaveBanners.addAll(mBanners);
            showBannerPager(mBanners);
            String zanNum = mOilDetailsModel.goodCount;
            TextViewUtils.setSpannableStyleColor(zanNum + "人点赞", 0, zanNum.length(), mTxtZanNum, R.color.color_main);
            mSaveTotalPic = mBanners.size();
            mTxtPicLocation.setText("1/" + mSaveTotalPic);
        } else {
            mLayoutBanner.setVisibility(View.GONE);
        }
        mTxtOilAddress.setText(mOilDetailsModel.location);
        mTxtOilCategory.setText(mOilDetailsModel.oilSourceName);
        if (mOilDetailsModel.isInvoice == 1) {
            mTxtIsInvoce.setText("可开发票");
        } else {
            mTxtIsInvoce.setText("不可开发票");
        }
        if (TextUtils.equals("1", mOilDetailsModel.isRecommend)) {
            //推荐
            mImgRecommend.setVisibility(View.VISIBLE);
        } else {
            mImgRecommend.setVisibility(View.GONE);
        }
        String mOilTitle = "";
        if (mOilDetailsModel.oilType == 1) {
            mOilTitle = "柴油 0# " + (TextUtils.equals("1", mOilDetailsModel.oilModel) ? "国IV" : "国V");
        }
        mTxtOilTitle.setText(mOilTitle);

        mLinearPrice.removeAllViews();
        mLinearPrice.addView(mTxtOilPrice);

        if (mOilDetailsModel.payType == 1) {
            //面议
//            mTxtOilPrice.setText("面议");
            mTxtOilPrice.setText("面议单价：" + Currency.returnDollar(mOilDetailsModel.tonPrice) + "/吨");
        } else if (mOilDetailsModel.payType == 2 || mOilDetailsModel.payType == 3) {
            //线上支付
            mTxtOilPrice.setText("单价：" + Currency.returnDollar(mOilDetailsModel.tonPrice) + "/吨");
        }
        List<OilDetailTagModel> mTags = mOilDetailsModel.tagList;
        if (null != mTags && !mTags.isEmpty()) {
            for (OilDetailTagModel model : mTags) {
                View mView = getLayoutInflater().inflate(R.layout.txt_oil_detail_tag, null);
                CardView mCardView = (CardView) mView.findViewById(R.id.id_oil_detail_cardview);
                mCardView.setCardBackgroundColor(model.tagsColor.contains("#") ? Color.parseColor(model.tagsColor) : Color.parseColor("#" + model.tagsColor));
                TextView mTxtName = (TextView) mView.findViewById(R.id.id_oil_tag_txt);
                mTxtName.setText(model.tagsName);
                mLinearPrice.addView(mView);
            }
        }
        if (TextUtils.equals("-1", mOilDetailsModel.stock)) {
            mTxtOilKucun.setText("- -");
        } else {
            mTxtOilKucun.setText("库存:" + StringUtils.returnKG(mOilDetailsModel.stock));
        }
        mTxtCompanyName.setText(mOilDetailsModel.orgName);
        mTxtOilType.setText(TextUtils.equals("1", mOilDetailsModel.oilModel) ? "国IV" : "国V");
        mTxtOilDensity.setText(mOilDetailsModel.oilDensity);
        mTxtCommentNum.setText("用户评价（" + mOilDetailsModel.commentCount + "）");

        handSendWay();
    }

    /**
     * 处理banner显示
     */
    public void showBannerPager(List<OilDetailBannerModel> mBanners) {
        mBannerAdp = new OilDetailBannerAdapter(mBanners, aty);
        mViewpager.setAdapter(mBannerAdp);
        mIndicator.setViewPager(mViewpager);
        mViewpager.setCurrentItem(0);
    }


    /**
     * 处理配送方式
     */
    public void handSendWay() {
        int sendWay = mOilDetailsModel.deliveryMode;
        if (sendWay == -1) {
            //自提
            mTransitPresenter.getSystemConstant("since_min", ConstantTag.GET_SINCE_MIN);
            //配送
            mTransitPresenter.getSystemConstant("distribution_min", ConstantTag.GET_DISTRIBUTION_MIN);
            mTxtOilZitiWay.setVisibility(View.VISIBLE);
            mTxtOilSendWay.setVisibility(View.VISIBLE);
        } else if (sendWay == 1) {
            //自提
            mTransitPresenter.getSystemConstant("since_min", ConstantTag.GET_SINCE_MIN);
            mTxtOilZitiWay.setVisibility(View.VISIBLE);
            mTxtOilSendWay.setVisibility(View.GONE);
        } else if (sendWay == 2) {
            //配送
            mTransitPresenter.getSystemConstant("distribution_min", ConstantTag.GET_DISTRIBUTION_MIN);
            mTxtOilZitiWay.setVisibility(View.GONE);
            mTxtOilSendWay.setVisibility(View.VISIBLE);
        } else {
            mTxtOilZitiWay.setVisibility(View.GONE);
            mTxtOilSendWay.setVisibility(View.GONE);
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        mXRefreshView.stopRefresh();
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.GET_OIL_DETAIL)) {
                //获得柴油批发详情
                mOilDetailsModel = (OilDetailsModel) t;
                if (null != mOilDetailsModel) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handleData();
                        }
                    });
                }
            } else if (TextUtils.equals(tag, ConstantTag.GET_CALCULATE_LIST)) {
                //获得定金计算列表
                List<CalculateMoneyModel> mCalculates = (List<CalculateMoneyModel>) t;
                if (null != mCalculates && !mCalculates.isEmpty()) {
                    for (CalculateMoneyModel model : mCalculates) {
                        if (model.calculatedType == 1) {
                            //比例计算
                            mCalculateModel = model;
                        }
                    }
                }
            } else if (TextUtils.equals(tag, ConstantTag.GET_SINCE_MIN)) {
                // 自提
                ConstantModel model = (ConstantModel) t;
                if (null != model) {
                    mSaveZitiNum = StringUtils.returnKG(model.key).replace("吨", "");
                    String msg = "自提(" + mSaveZitiNum + "吨起)";
                    TextViewUtils.setSpannableStyleColor(msg, 3, (3 + mSaveZitiNum.length()), mTxtOilZitiWay, R.color.color_main);
                }
            } else if (TextUtils.equals(tag, ConstantTag.GET_DISTRIBUTION_MIN)) {
                // 配送
                ConstantModel model = (ConstantModel) t;
                if (null != model) {
                    mSaveSendNum = StringUtils.returnKG(model.key).replace("吨", "");
                    String msg = "配送（" + mSaveSendNum + "吨起,不含运费)";
                    TextViewUtils.setSpannableStyleColor(msg, 3, (3 + mSaveSendNum.length()), mTxtOilSendWay, R.color.color_main);
                }
            }
        }
    }
}
